package com.itheima.app.manager;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.sms.SmsTemplate;
import com.itheima.domain.db.*;
import com.itheima.service.db.*;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.ErrorResult;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.SettingVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SettingManager {
    @DubboReference
    private QuestionService questionService;
    @DubboReference
    private NotificationService notificationService;
    @DubboReference
    private BlackListService blackListService;
    @DubboReference
    private UserInfoService userInfoService;
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @DubboReference
    private UserService userService;

    //查询通用部分
    public ResponseEntity findSettingVo() {
        //通过令牌获取user对象
        User user = UserHolder.get();
        //通过userid获取陌生人问题
        Question question = questionService.findByUserId(user.getId());
        //通过userid获取推送通知
        Notification notification = notificationService.findByUserId(user.getId());
        //创建通用设置信息类 封装
        SettingVo settingVo = new SettingVo();
        if (question != null) {
            settingVo.setStrangerQuestion(question.getStrangerQuestion());
        }
        if (notification != null) {
            settingVo.setGonggaoNotification(notification.getGonggaoNotification());
            settingVo.setLikeNotification(notification.getLikeNotification());
            settingVo.setPinglunNotification(notification.getPinglunNotification());
        }
        settingVo.setId(user.getId());
        settingVo.setPhone(user.getPhone());
        //返回页面
        return ResponseEntity.ok(settingVo);
    }
   //修改陌生人问题
    public void setQuestion(String content) {
        //根据token获取userId
        User user = UserHolder.get();
        Long id = user.getId();
        //调用业务层根据userId查询陌生人问题
        Question question = questionService.findByUserId(id);
        //判断是否为空
        if (question == null) {
            //为空新建问题实体类并赋值保存
            question = new Question();
            question.setStrangerQuestion(content);
            question.setUserId(id);
            questionService.save(question);
        } else {
            //不为空直接修改问题调用业务层修改
            question.setStrangerQuestion(content);
            questionService.update(question);
        }
    }
    //修改通知权限
    public void setNotification(Notification notification) {
        //根据token查询userId
        User user = UserHolder.get();
        Long id = user.getId();
        //根据userId查找通知权限设置
        Notification notificationById = notificationService.findByUserId(id);
        //判断是否为空
        if (notificationById == null) {
            //为空新建通知权限类赋值并保存
            notification.setUserId(id);
            notificationService.save(notification);
        } else {
            //不为空修改权限并且调用业务层修改
            notificationById.setPinglunNotification(notification.getPinglunNotification());
            notificationById.setLikeNotification(notification.getLikeNotification());
            notificationById.setGonggaoNotification(notification.getGonggaoNotification());
            notificationService.update(notificationById);
        }
    }
    //查询黑名单
    public ResponseEntity findBlackListByPage(Integer pageNum, Integer pageSize) {
        //根据token查询userId
        Long id = UserHolder.get().getId();
        //调用业务层查询黑名单并分页
        PageBeanVo pageBeanVo = blackListService.findByPage(id, pageNum, pageSize);
        //获取黑名单集合
        List<BlackList> items = (List<BlackList>) pageBeanVo.getItems();
        List list = new ArrayList();
        //判断非空
        if (items != null && items.size() > 0) {
            //遍历黑名单
            for (BlackList item : items) {
                //获取黑名单中的黑名单用户id
                Long blackUserId = item.getBlackUserId();
                //根据黑名单用户id查询该用户的详细信息
                UserInfo userInfo = userInfoService.findById(blackUserId);
                //把黑名单用户详细信息添加到list集合
                list.add(userInfo);
            }
            //把黑名单用户详细信息修改到分页中的集合
            pageBeanVo.setItems(list);
        }
        //向页面返回信息
        return ResponseEntity.ok(pageBeanVo);
    }
   //移除黑名单用户
    public void removeBlackList(Long blackUserId) {
        //根据token获取userid
        Long id = UserHolder.get().getId();
        //调用业务层删除
        blackListService.remove(id,blackUserId);
    }
    //发送验证码
    public void sendVerificationCode() {
        //根据token获取手机号
        String phone = UserHolder.get().getPhone();
        //生成验证码
        String code = RandomUtil.randomNumbers(6);
        //方便测试 TODO
        code="123456";
        //smsTemplate.sendSms(phone,code);
        //把验证码存入redis 有效期5分钟
        stringRedisTemplate.opsForValue().set(ConstantUtil.SMS_CODE+UserHolder.get().getId(),code, Duration.ofMinutes(5));
    }
    //检测验证码
    public ResponseEntity checkVerificationCode(String code) {
        //根据token获取userId
        Long userId = UserHolder.get().getId();
        //从redis里获取存入验证码
        String redisCode = stringRedisTemplate.opsForValue().get(ConstantUtil.SMS_CODE + userId);
        Boolean verification=true;
        //判断redis里验证码是否为空
        if (StrUtil.isEmpty(redisCode)){
            verification=false;
            return ResponseEntity.status(500).body(verification);
        }
        //判断页面传入验证码是否为空
        if (StrUtil.isEmpty(code)){
            verification=false;
            return ResponseEntity.status(500).body(verification);

        }
        //判断两个验证码是否一致
        if (!redisCode.equals(code)){
            verification=false;
            return ResponseEntity.status(500).body(verification);
        }
        //定义map返回值
        Map<String ,Boolean > map=new HashMap<>();
        //返回值存入map
        map.put("verification",verification);
        //返回页面
        return ResponseEntity.ok(map);
    }
   //修改手机号
    public void setPhone(String phone) {
        //根据token获取userId
        Long userId = UserHolder.get().getId();
        //创建user对象 并赋值
        User user = new User();
        user.setId(userId);
        user.setPhone(phone);
        //调用service修改手机号
        userService.updatePhoneById(user);
    }
}
